package Com.Ring.TradingMobile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.Common.MARKET;
import Com.Ring.TradingMobile.Object.CompanyInfo;
import Com.Ring.TradingMobile.Object.Config;
import Com.Ring.TradingMobile.Object.DanhMuc;
import Com.Ring.TradingMobile.Object.ItemDanhMuc;
import Com.Ring.TradingMobile.Object.MarketInfo;
import Com.Ring.TradingMobile.Object.StockInfo;
import Com.Ring.TradingMobile.SQLite.DBManager;
import Com.Ring.TradingMobile.Service.WebService;
import android.R.layout;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class ThiTruongActivity extends Activity {

	private static final int DIALOG_LOADING = 0;

	public boolean IsRealTime = true;
	public long Interval = 10000;

	public MARKET marketEnum;
	private DanhMuc danhMuc;

	private int[] StrHeaderId = new int[]{R.string.strMaCK, R.string.strRef,
			R.string.strCeiling, R.string.strFloor, R.string.strLast,
			R.string.strChange, R.string.strVol, R.string.strBestBuyPrice,
			R.string.strBestBuyVol, R.string.strBestSellPrice,
			R.string.strBestSellVol, R.string.strTotalVol};

	private Spinner DropListMarket;
	private CheckBox CheckRealTime;
	private AutoCompleteTextView AutoCompleteStock;
	private LinearLayout linearHeader;
	private LinearLayout linearContent;
	private TextView lblIndex;
	private TextView lblKLAndGT;
	private TextView lblStatusCurrent;
	private TextView lblDanhMuc;
	private Button btnBack;
	private Button btnHome;
	private Button btnRefresh;
	private Button btnThem;
	private Button btnXoa;

	private Handler updaterHandler;
	private ExecutorService updaterExecutor;
	private Runnable updaterRunnable = null;
	private Future<?> updaterFuture;

	public boolean IsUpdateCompany;
	public boolean IsUpdateStockInfoRunning;
	public boolean IsRunningUpdate;
	public boolean IsSave;
	public boolean IsReady = false;
	private int PositionDropListMarket = 0;

	private String TAG = "ThiTruong";

	public List<String> CodeArray = new ArrayList<String>();

	private Class<? extends Activity> ActivityCallBack;

	Handler AutoHanlerUpdate = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			UpdateTask(1);
		}
	};

	private Thread AutoThreadUpdate = new Thread(new Runnable() {
		public void run() {
			Long sleep = (long) 1;
			// if(updaterRunnable==null) {
			// InitThread();
			// }
			while (IsRunningUpdate) {
				try {
					Thread.sleep(sleep * 1000);
				} catch (InterruptedException e) {
					Log.d(TAG, e.toString());
				}
				sleep = Interval;
				AutoHanlerUpdate.sendMessage(AutoHanlerUpdate.obtainMessage());
			}
		}
	});

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case DIALOG_LOADING : {
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Please wait while loading...");
				dialog.setIndeterminate(true);
				dialog.setCancelable(true);
				return dialog;
			}
		}
		return null;
	}

	@Override
	protected void onPause() {
		Common.StopTimer();
		try {

			if (AutoThreadUpdate.isAlive()) {
				IsRunningUpdate = false;
				AutoThreadUpdate.stop();
			}
			IsReady = false;
			updaterExecutor.shutdown();
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
		Log.d(TAG, "On Pause");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		Log.d(TAG, "On Restart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// IsUpdateCompany = true;
		// IsRunningUpdate = true;
		// InitThread();
		// AutoThreadUpdate.start();
		Log.d(TAG, "On Resume");
		super.onResume();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.thitruong_main);
		// get data from another activity
		danhMuc = new DanhMuc();
		Bundle bund = getIntent().getExtras();
		String[] arrayStr = bund.getStringArray(Common.KeyIntentThiTruong);
		marketEnum = Common.ConvertToEnumMarket(Integer.parseInt(arrayStr[0]));
		DBManager dbData = new DBManager(this);
		Cursor cur = dbData.Select("select * from " + DanhMuc.TABLE_NAME
				+ " where " + DanhMuc.NAME_DANH_MUC + " = '" + arrayStr[1]
				+ "' ");
		ActivityCallBack = arrayStr[2].equals("0")
				? TradingMobileActivity.class
				: DanhMucActivity.class;
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				danhMuc.Name_Danh_Muc = cur.getString(cur
						.getColumnIndex(DanhMuc.NAME_DANH_MUC));
				danhMuc.Id_Danh_Muc = cur.getInt(cur
						.getColumnIndex(DanhMuc.ID_DANH_MUC));
			}
		}
		dbData.close();
		CodeArray = GetCodesFromList(danhMuc.Id_Danh_Muc);
		FindViewById();
		InitControlListener();
		BindingData();
		InitThread();

		Log.d(TAG, "On Create");

	}

	private List<String> GetCodesFromList(int idDanhMuc) {
		DBManager dbData = new DBManager(this);
		List<String> listCode = new ArrayList<String>();
		try {
			Cursor cur = dbData.Select("select " + ItemDanhMuc.CODE + " from "
					+ ItemDanhMuc.TABLE_NAME + " where "
					+ ItemDanhMuc.ID_DANH_MUC + " = " + idDanhMuc + " ");
			if (cur.getCount() > 0) {
				while (cur.moveToNext()) {
					listCode.add(cur.getString(cur
							.getColumnIndex(ItemDanhMuc.CODE)));
				}
			}
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		} finally {
			if (dbData != null) {
				dbData.close();
			}
		}
		return listCode;
	}

	private boolean IsConnectNetwork() {
		final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conMgr.getActiveNetworkInfo() != null
				&& conMgr.getActiveNetworkInfo().isAvailable()
				&& conMgr.getActiveNetworkInfo().isConnected()) {
			return true;
		} else {
			return false;
		}

	}

	OnItemSelectedListener ListenerDropListMarket = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			if (position != PositionDropListMarket) {
				PositionDropListMarket = position;
				marketEnum = Common.ConvertToEnumMarket(position + 1);
				// if(IsReady)
				// UpdateTask(1);
			}
		}
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	};

	private void BindingData() {
		// Auto Check RealTime
		DBManager dbData = new DBManager(this);
		Cursor cur = dbData.Select("select * from " + Config.TABLE_NAME);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				IsRealTime = cur.getInt(cur.getColumnIndex(Config.IS_REALTIME)) == 1
						? true
						: false;
				IsSave = cur.getInt(cur.getColumnIndex(Config.AUTO_SAVE)) == 1
						? true
						: false;
				Interval = cur.getLong(cur.getColumnIndex(Config.INTERVAL));

			}
		}
		CheckRealTime.setChecked(IsRealTime);
		// Binding data for Drop Down list Market
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.Market, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		DropListMarket.setAdapter(adapter);
		DropListMarket.setSelection(1);
		lblDanhMuc.setText(danhMuc.Name_Danh_Muc);
	}

	private void FindViewById() {
		DropListMarket = (Spinner) findViewById(R.id.dropDownListMarket);
		CheckRealTime = (CheckBox) findViewById(R.id.chkRealTime);
		AutoCompleteStock = (AutoCompleteTextView) findViewById(R.id.autoCompleteMarket);
		AutoCompleteStock.setThreshold(1);
		linearHeader = (LinearLayout) findViewById(R.id.linearHeader);
		linearContent = (LinearLayout) findViewById(R.id.linearContent);
		lblIndex = (TextView) findViewById(R.id.lblIndex);
		lblKLAndGT = (TextView) findViewById(R.id.lblKLAndGT);
		lblStatusCurrent = (TextView) findViewById(R.id.lblStatusCurrent);
		lblDanhMuc = (TextView) findViewById(R.id.lblDanhMuc);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnHome = (Button) findViewById(R.id.btnHome);
		btnRefresh = (Button) findViewById(R.id.btnRefresh);
		btnThem = (Button) findViewById(R.id.btnThem);
		btnXoa = (Button) findViewById(R.id.btnXoa);

		/*
		 * Initialization Create Header
		 */
		TableLayout tableHeader = new TableLayout(this);
		TableRow[] rowsHeader = new TableRow[StrHeaderId.length];
		TextView[] txtHeader = new TextView[StrHeaderId.length];
		for (int i = 0; i < txtHeader.length; i++) {
			rowsHeader[i] = new TableRow(this);
			txtHeader[i] = new TextView(this);
			txtHeader[i].setText(StrHeaderId[i]);
			txtHeader[i].setHeight(24);
			txtHeader[i].setTextSize(12);
			txtHeader[i]
					.setBackgroundResource(R.drawable.border_color_textview);
			txtHeader[i].setTextColor(getResources().getColor(R.color.whiles));
			rowsHeader[i].addView(txtHeader[i]);
			tableHeader.addView(rowsHeader[i]);
		}
		linearHeader.addView(tableHeader);

	}
	private void InitControlListener() {
		btnThem.setOnClickListener(themListener);
		btnXoa.setOnClickListener(xoaListener);
		CheckRealTime.setOnCheckedChangeListener(listenerRealtime);
		DropListMarket.setOnItemSelectedListener(ListenerDropListMarket);
		btnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						ActivityCallBack);
				startActivity(intent);
				finish();
			}
		});
		btnHome.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						ActivityCallBack);
				startActivity(intent);
				finish();
			}
		});
		btnRefresh.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				UpdateTask(1);
			}
		});
	}

	/*
	 * Event Listen
	 */

	OnCheckedChangeListener listenerRealtime = new OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			IsRealTime = isChecked;
			if (IsRealTime) {
				if (!AutoThreadUpdate.isAlive()) {
					AutoThreadUpdate.run();
				}
			} else {
				IsRunningUpdate = false;
			}
		}
	};
	OnClickListener themListener = new OnClickListener() {
		public void onClick(View v) {
			String code = AutoCompleteStock.getText().toString().trim();
			if (!code.equals("") && code.length() >= 3) {
				AutoCompleteStock.setText("");
				if (!CodeArray.contains(code)) {
					DBManager dbData = new DBManager(ThiTruongActivity.this);
					dbData.InsertItemDanhMuc(danhMuc.Id_Danh_Muc, code);
					dbData.close();
					CodeArray.add(0, code);
					UpdateTask(1);
				}
			}
		}
	};

	OnClickListener xoaListener = new OnClickListener() {
		public void onClick(View v) {
			String code = AutoCompleteStock.getText().toString().trim();
			if (!code.equals("") && code.length() >= 3) {
				AutoCompleteStock.setText("");
				if (CodeArray.contains(code)) {
					CodeArray.remove(code);
					DBManager dbData = new DBManager(ThiTruongActivity.this);
					dbData.DeleteItemDanhMuc(danhMuc.Id_Danh_Muc, code);
					dbData.close();
					if (CodeArray.isEmpty())
						linearContent.removeAllViewsInLayout();
					else
						UpdateTask(1);
				}
			}
		}
	};

	private void InitThread() {
		updaterHandler = new Handler();
		updaterExecutor = Executors.newSingleThreadExecutor();
		updaterRunnable = new Runnable() {
			public void run() {
				if (IsReady) {
					Log.d(TAG, "Running....");
					if (updaterFuture != null) {
						updaterFuture.cancel(true);
					}
					ThiTruongTask thiTruongTask = new ThiTruongTask(
							ThiTruongActivity.this, IsUpdateCompany, CodeArray,
							marketEnum, IsRealTime, IsSave);
					updaterFuture = updaterExecutor.submit(thiTruongTask);
				}
			}
		};
	}

	public void UpdateMarketInfo(MarketInfo marketInfo) {
		try {
			Log.d(TAG, "Running Update MarketInfo");
			UpdateMarketInfoUIThread(lblIndex, lblKLAndGT, lblStatusCurrent,
					marketInfo);
			Log.d(TAG, "Done Update MarketInfo");
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}

	private void UpdateMarketInfoUIThread(final TextView txtIndex,
			final TextView txtKLAndGT, final TextView txtStatus,
			final MarketInfo marketInfo) {
		updaterHandler.post(new Runnable() {
			public void run() {
				String setIndex = Common.FormatShortNumber(marketInfo.SetIndex);
				String indexChange = Common
						.FormatShortNumber(marketInfo.IndexChanged);
				String totalValue = Common
						.FormatShortNumber(marketEnum == MARKET.HOSE
								? marketInfo.TotalValues * 100000
								: marketInfo.TotalValues);
				String volume = Common
						.FormatShortNumber(marketInfo.TotalShares);
				float ref = marketInfo.SetIndex - marketInfo.IndexChanged;
				String perChange = ref > 0
						? Common.FormatShortNumber(marketInfo.IndexChanged
								/ ref * 100)
						: "0";
				txtIndex.setText(setIndex + " " + indexChange + "(" + perChange
						+ ")");
				txtIndex.setTextColor(getResources().getColor(
						SetColorMarketInfo(marketInfo.IndexChanged)));
				txtKLAndGT.setText(volume + " | " + totalValue);
				txtKLAndGT
						.setTextColor(getResources().getColor(R.color.whiles));

				txtStatus.setText(getResources().getString(
						Common.GetMarketStatus(marketEnum, marketInfo.Status)));

			}

			private int SetColorMarketInfo(float indexChange) {
				if (indexChange > 0)
					return R.color.up;
				else if (indexChange < 0)
					return R.color.down;
				return R.color.nochange;
			}
		});
	}

	public void UpdateListStockInfo(List<StockInfo> listStockInfo) {
		try {
			Log.d(TAG, "Running Create Table Content");
			UpdateStockInfoUIThread(linearContent, listStockInfo);
			Log.d(TAG, "Done create Table Content");
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}

	private void UpdateStockInfoUIThread(final LinearLayout linearContent,
			final List<StockInfo> listStockInfo) {
		updaterHandler.post(new Runnable() {
			public void run() {
				if (listStockInfo != null && listStockInfo.size() > 0) {
					linearContent.removeAllViewsInLayout();
					String text = null;
					int color = 0;
					for (StockInfo stockInfo : listStockInfo) {
						TableLayout tableContent = new TableLayout(
								ThiTruongActivity.this);
						TableRow[] rowContents = new TableRow[StrHeaderId.length];
						TextView[] txtContent = new TextView[StrHeaderId.length];
						for (int i = 0; i < txtContent.length; i++) {
							rowContents[i] = new TableRow(
									ThiTruongActivity.this);
							txtContent[i] = new TextView(ThiTruongActivity.this);
							// set text
							switch (i) {
								case 0 :
									text = stockInfo.Symbol;
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 1 :
									text = Common
											.FormatNumber(stockInfo.RefPrice);
									color = R.color.nochange;
									break;
								case 2 :
									text = Common
											.FormatNumber(stockInfo.CeilPrice);
									color = R.color.ceilling;
									break;
								case 3 :
									text = Common
											.FormatNumber(stockInfo.FloorPrice);
									color = R.color.floor;
									break;
								case 4 :
									text = Common
											.FormatNumber(stockInfo.PriceMatch);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 5 :
									text = Common
											.FormatNumber(stockInfo.Changed);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 6 :
									text = Common
											.FormatNumber(stockInfo.VolumeMatch);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 7 :
									text = Common
											.FormatNumber(stockInfo.BestPriceBuy);
									color = SetColorStockInfo(
											stockInfo.BestPriceBuy,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 8 :
									text = Common
											.FormatNumber(stockInfo.BestVolbuy);
									color = SetColorStockInfo(
											stockInfo.BestPriceBuy,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 9 :
									text = Common
											.FormatNumber(stockInfo.BestPriceSell);
									color = SetColorStockInfo(
											stockInfo.BestPriceSell,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 10 :
									text = Common
											.FormatNumber(stockInfo.BestVolSell);
									color = SetColorStockInfo(
											stockInfo.BestPriceSell,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 11 :
									text = Common
											.FormatNumber(stockInfo.TotalMatch);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
							}
							txtContent[i].setText(text);
							txtContent[i].setTextColor(getResources().getColor(
									color));
							txtContent[i].setHeight(24);
							txtContent[i].setTextSize(12);
							txtContent[i].setGravity(Gravity.RIGHT);
							txtContent[i].setPadding(0, 0, 2, 0);
							LayoutParams layout = new LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT);
							// layout.width = 50;
							txtContent[i].setLayoutParams(layout);

							txtContent[i]
									.setBackgroundResource(R.drawable.border_color_textview);
							rowContents[i].addView(txtContent[i], layout);
							tableContent.addView(rowContents[i]);
						}
						// add row virtual
						TableRow rowVirtual = new TableRow(
								ThiTruongActivity.this);
						tableContent.addView(rowVirtual);
						//
						linearContent.addView(tableContent);
					}
				}
			}

			private int SetColorStockInfo(float price, float ceil, float floor,
					float ref) {
				int color = 0;

				if (price == ceil)
					color = R.color.ceilling;
				else if (price == ref)
					color = R.color.nochange;
				else if (price == floor)
					color = R.color.floor;
				else if (price > ref)
					color = R.color.up;
				else if (price > floor)
					color = R.color.down;
				else
					color = R.color.whiles;

				return color;
			}
		});
	}

	public void UpdateCompany(List<CompanyInfo> listCompany) {
		if (listCompany.size() > 0) {
			String[] arrayCode = new String[listCompany.size()];
			int i = 0;
			for (CompanyInfo company : listCompany) {
				arrayCode[i++] = company.Code;
			}
			try {
				UpdateCompanyUIThread(arrayCode, AutoCompleteStock);

			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
		}
	}

	public void ShowDialog() {
		updaterHandler.post(new Runnable() {
			public void run() {
				showDialog(DIALOG_LOADING);
			}
		});
	}

	public void RemoveDialog() {
		updaterHandler.post(new Runnable() {
			public void run() {
				removeDialog(DIALOG_LOADING);
			}
		});
	}

	private void UpdateCompanyUIThread(final String[] arrayCode,
			final AutoCompleteTextView auto) {
		updaterHandler.post(new Runnable() {
			public void run() {
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						ThiTruongActivity.this,
						android.R.layout.simple_dropdown_item_1line, arrayCode);
				auto.setAdapter(adapter);
			}
		});
	}

	private void UpdateTask(int delay) {
		updaterHandler.removeCallbacks(updaterRunnable);
		updaterHandler.postDelayed(updaterRunnable, delay);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Runnable runable = new Common.CountDownRunner();
		Common.StartTimer(runable, ThiTruongActivity.this);
		IsUpdateCompany = true;
		IsRunningUpdate = true;
		IsReady = true;
		AutoThreadUpdate.start();
		Log.d(TAG, "On Start");

	}

	@Override
	protected void onStop() {
		Log.d(TAG, "On Stop");
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "On Destroy");
		super.onDestroy();
	}

}
